package com.swordxu.yim.server.tool.mananger;

import com.swordxu.yim.server.dbproxy.model.Department;
import com.swordxu.yim.server.dbproxy.model.User;
import com.swordxu.yim.server.packet.AllContactsPacket;
import com.swordxu.yim.server.packet.DepartmentPacket;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * 联系人业务处理类
 * Created by 徐晓明 on 2015/1/13.
 */
public class ContactManager {
    private Logger logger = Logger.getLogger(ContactManager.class);
    private static ContactManager cmg;
    private static ChannelHandlerContext channel;

    /**
     * 获取ContactManager实例
     * @param channel
     * @return
     */
    public static ContactManager instance(ChannelHandlerContext channel) {
        synchronized (ContactManager.class) {
            if (cmg == null) {
                cmg = new ContactManager();
                cmg.channel = channel;
            }
            return cmg;
        }
    }

    /**
     * 处理客户端请求部门列表数据
     * @param buffer
     */
    public void reqGetDepartments(String buffer) {
        System.out.println("处理客户端请求部门列表数据");
        DepartmentPacket dp = new DepartmentPacket();
//        dp.decode(buffer);
        List<Department> list = Department.dao.find("select * from t_department");
        DepartmentPacket.PacketResponse rs = new DepartmentPacket.PacketResponse(list);
        dp.setmResponse(rs);
        channel.writeAndFlush(dp.encode());
        System.out.println("返回部门列表:" + dp.encode());
    }

    /**
     * 处理客户端获取所有联系人数据请求
     * @param buffer
     */
    public void reqGetAllContacts(String buffer) {
        logger.info("处理客户端请求返回所有联系人");
        AllContactsPacket acp = new AllContactsPacket();
        List<User> list = User.dao.find("select * from t_user");
        AllContactsPacket.PacketResponse rs = new AllContactsPacket.PacketResponse(list);
        acp.setmResponse(rs);
        channel.writeAndFlush(acp.encode());
        logger.info("返回所有联系人列表" + acp.encode());
    }
}
